package com.itheima.web.request; /**
 * @author Xiao
 * @date 2021/8/29
 */

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**请求参数中文乱码问题：GET*/
@WebServlet(name = "RequestDemo07", value = "/demo07")
public class RequestDemo07 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求参数
        String username = request.getParameter("username");
        System.out.println("解决乱码前：" + username);
        //1. 解决POST请求参数的中文乱码问题
        request.setCharacterEncoding("UTF-8");
        username = request.getParameter("username");
        System.out.println("POST请求解决乱码：" + username);
        //2. 解决GET请求参数的中文乱码问题
        /*byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
        username = new String(bytes, StandardCharsets.UTF_8);*/
        username = new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        System.out.println("GET请求解决乱码：" + username);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
